package com.malf.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.malf.entity.NBAPlayer;
import com.malf.service.NBAPlayerService;
import com.malf.util.RedisUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author malf
 * @description
 * @date 2021/5/23
 * @project springboot_mybatis
 */
@RestController
@RequestMapping("/redis")
public class RedisController {

	@Resource
	private RedisUtils redisUtils;
	@Resource
	private NBAPlayerService nbaPlayerService;

	@RequestMapping("setAndGet")
	public String test(String k, String v) {
		redisUtils.set(k, v);
		return (String) redisUtils.get(k);
	}

	@RequestMapping("test")
	public Object test() {
		// step1 先从redis中取
		String strJson = (String) redisUtils.get("nbaPlayerCache");
		if (strJson == null) {
			System.out.println("从db取值");
			// step2如果拿不到则从DB取值
			List<NBAPlayer> listNbaPlayer = nbaPlayerService.list();
			// step3 DB非空情况刷新redis值
			if (listNbaPlayer != null) {
				redisUtils.set("nbaPlayerCache", JSON.toJSONString(listNbaPlayer));
				return listNbaPlayer;
			}
			return null;
		} else {
			System.out.println("从redis缓存取值");
			return JSONObject.parseArray(strJson, NBAPlayer.class);
		}
	}

}
